package top.go2do.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import top.go2do.common.httpResponseResult.ApiResponse;

import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

/**
 * @author xingyuji
 * @date 2025/3/9 18:09
 * @description
 */
@Order(99)
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @Autowired
    private MessageSource messageSource;

    /**
     * 已知的业务异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public ApiResponse<?> handleBusinessException(BusinessException ex) {
        String msg = resolveMessage(ex.getMsgKey(), ex.getArgs(), LocaleContextHolder.getLocale());
        return ApiResponse.error(ex.getCode(), msg);
    }

    @ExceptionHandler(HttpMediaTypeException.class)
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    public ApiResponse<?> handleHttpMessageNotSupportedException(HttpMediaTypeException ex) {
        HttpStatus httpStatus = HttpStatus.UNSUPPORTED_MEDIA_TYPE;
        return ApiResponse.error(httpStatus.value(), httpStatus.getReasonPhrase());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse handleValidationException(MethodArgumentNotValidException ex, WebRequest request) {
        BindingResult bindingResult = ex.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();

        // 获取请求的 Locale（如通过请求头 Accept-Language）
        Locale locale = request.getLocale();

        BusinessResultCode invalidParam = BusinessResultCode.INVALID_PARAMETER;
        String msg = resolveMessage(invalidParam.getMsgKey(), null, locale);
        List<String> errors = fieldErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList());

        ApiResponse response = ApiResponse.error(invalidParam.getCode(), msg);
        response.setData(errors);
        return response;
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ApiResponse<?> handleOtherException(Exception ex) {
        log.error("500_error:", ex);
        return ApiResponse.error(BusinessResultCode.INTERNAL_ERROR.getCode(), ex.getMessage());
    }

    private String resolveMessage(String messageKey, @Nullable Object[] args, Locale locale) {
        try {
            // 通过 MessageSource 解析消息
            return messageSource.getMessage(messageKey, args, locale);
        } catch (NoSuchMessageException e) {
            log.warn("i18n message not found key:{}, lang:{}", messageKey, locale.toLanguageTag());
            return messageKey;
        }
    }
}
